﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;

namespace DeviceManager.Controllers
{
    public class FileController : Controller
    {
        //
        // GET: /File/
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult AjaxUpload()
        {
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        [HttpPost]
        [Authorize]
        public ActionResult AjaxUploadFile(HttpPostedFileBase FileData)
        {
            string result = "";
            if (null != FileData)
            {
                try
                {
                    result = Path.GetFileName(FileData.FileName);//获得文件名
                    string ext = Path.GetExtension(FileData.FileName);//获得文件扩展名
                    string saveName = "uploadfile" + ext;//实际保存文件名
                    //saveFile(FileData, folder, saveName);//保存文件
                }
                catch
                {
                    result = "";
                }
            }
            return Json(result);
        }    

        public ActionResult Upload()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Upload(string id)
        {
            var path = Server.MapPath("/Content/Upload/");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            for (int i = 0; i < Request.Files.Count; i++)
            {
                if (Request.Files[i].ContentLength > 0)
                {
                    var fileName = Request.Files[i].FileName.Substring(Request.Files[i].FileName.LastIndexOf('\\') + 1, Request.Files[i].FileName.Length - Request.Files[i].FileName.LastIndexOf('\\') - 1);
                    Request.Files[i].SaveAs(path + fileName);
                    //将文件路径path+fileName写入数据库
                }
            }
            return View();
        }
        //文件列表
        public ActionResult FileList()
        {
            string path = Server.MapPath("/Content/Upload/");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            ViewBag.files= Directory.GetFiles(path);
            return View();
        }
        //文件下载
        public FilePathResult Download(string id)
        {
            System.Diagnostics.Trace.WriteLine(id);
            return File("/Content/Upload/" + id, "image/jpeg", id);
        }
    }
}
